<!-- 单位编辑弹窗 -->
<template>
  <ele-modal v-model="visible" form :width="420" title="导入商品">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="货主" prop="supplier_id">
        <el-select v-model="form.supplier_id" placeholder="请选择货主" clearable>
          <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="货主" prop="file">
        <el-upload
          ref="uploadRef"
          v-model:file-list="form.file"
          class="w-full"
          accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          :limit="1"
          :on-exceed="handleExceed"
          :auto-upload="false"
        >
          <template #trigger>
            <el-button type="primary" plain>选择附件</el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="flex-ba">
        <el-link type="primary" icon="IconElDownload" @click="openUrl">商品导入模板</el-link>
        <div>
          <el-button @click="updateModelValue(false)">
            取消
          </el-button>
          <el-button type="primary" :loading="loading" @click="save">
            保存
          </el-button>
        </div>
      </div>
    </template>
  </ele-modal>
</template>

<script setup>
import { ElDivider, ElMessageBox, ElTable, ElTableColumn } from 'element-plus'

defineProps({
  supplierList: Array,
})
const emit = defineEmits(['done'])

const visible = defineModel()

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

/** 表单数据 */
const [form, resetFields] = utils.useFormData({
  file: [],
  supplier_id: '',
})

/** 表单验证规则 */
const rules = reactive({
  file: [
    {
      required: true,
      message: '请选择附件',
      trigger: 'change',
    },
  ],
  supplier_id: [
    {
      required: true,
      message: '请选择货主',
      trigger: 'change',
    },
  ],
})

const uploadRef = ref(null)

function handleExceed(files) {
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = useId()
  uploadRef.value.handleStart(file)
}

function openUrl() {
  window.open(`${import.meta.env.VITE_API_URL}/static/商品导入模板.xlsx`)
}
/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    const formData = new FormData()
    formData.append('file', form.file[0].raw)
    formData.append('supplier_id', form.supplier_id)

    utils.post('/product/import', formData)
      .then((res) => {
        if (!res.success) {
          return utils.message(res.msg, 'error')
        }
        updateModelValue(false)
        emit('done')

        const nodes = [
          h('div', {}, [
            '共新增',
            h('span', { class: 'text-success mx-2px text-16px font-bold' }, res.data.success_num),
            '条数据，失败',
            h('span', { class: 'text-danger mx-2px text-16px font-bold' }, res.data.error_num),
            '条数据。',
          ]),
        ]
        if (res.data.error_num > 0) {
          nodes.push(
            h(ElDivider, { contentPosition: 'left' }, () => '商品导入失败明细'),
            h(ElTable, { data: res.data.error_data, size: 'small', stripe: true }, () => [
              [
                h(ElTableColumn, {
                  type: 'index',
                  label: '序',
                  width: 40,
                }),
                h(ElTableColumn, {
                  prop: 'name',
                  label: '商品名称',
                  minWidth: 100,
                }),
                h(ElTableColumn, {
                  prop: 'msg',
                  label: '错误描述',
                  minWidth: 140,
                }),
              ],
            ]),
          )
        }

        ElMessageBox
          .alert(
            h('div', {}, nodes),
            '导入完成',
            {
              dangerouslyUseHTMLString: true,
              type: 'success',
              confirmButtonText: '知道了',
              draggable: true,
            },
          )
          .then(() => {})
          .catch(() => {})
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新visible */
function updateModelValue(value) {
  visible.value = value
}

watch(
  () => visible.value,
  (val) => {
    if (val)
      resetFields()
  },
)
</script>
